package com.db.service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.db.bean.Dlt;
import com.db.dao.DU;
import com.db.util.Netutil;

import cn.hutool.db.Entity;

@Service
public class DltService {

	public int saveLast() {
		// 获得最新的数据
		String last = Netutil.getLast("http://www.lottery.gov.cn/lottery_index_kj.json");
		// 判断数据库是否是最新的
		Dlt dlt = toDlt(last);
		if (null != dlt && null != dlt.getTerm()) {
			// 获得最新
			Entity e = getFromDb(dlt.getTerm());
			if (e == null) {
				// 转换
				e = toEntity(dlt.getNumberCode());
				e.put("was_history", 1);
				e.put("term_start", dlt.getTerm());
				// 保存
				return saveDlt(e);
			}
		}
		return 0;
	}
	
	public String getLastInfo() {
		
		return "";
	}

	public int saveDlt(Entity e) {
		e.setTableName("leto");
		try {
			// 存数据
			return DU.getDb().insert(e);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		return 0;
	}

	public Entity toEntity(List<String> zjhs) {
		Entity e = new Entity();
		e = new Entity();
		for (int i = 1; i <= zjhs.size(); i++) {
			if (i < 6) {
				e.put("r" + i, zjhs.get(i - 1));
			} else {
				e.put("b" + (i - 5), zjhs.get(i - 1));
			}
		}
		return e;
	}

	public Entity getFromDb(String term) {
		try {
			return DU.getDb().queryOne("select * from leto where was_history = 1 and term_start = ?", term);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Dlt toDlt(String json) {
		if (null != json) {
			JSONArray jarr = JSON.parseArray(json);
			if (null != jarr) {
				JSONObject jobj = (JSONObject) jarr.get(0);
				if (jobj != null) {
					return jobj.getObject("dlt", Dlt.class);
				}
			}
		}
		return null;
	}

	public int saveMy(String my) {
		List<String> zjhs = Arrays.asList(my.split("#"));
		Entity e = toEntity(zjhs);
		e.put("was_history", 2);
		e.put("term_start", 19027);
		e.put("term_end", 19042);
		return saveDlt(e);
	}

	/*
	 * public static void main(String[] args) { DltService ser = new DltService();
	 * ser.saveMy("02#07#11#16#18#01#05"); ser.saveMy("02#07#11#16#18#01#06");
	 * ser.saveMy("02#07#11#16#18#05#06"); }
	 */
}
